package com.ht.api.call.func.impl.ad;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.business.ad.PlanHelper;
import com.ht.api.call.ICall;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.util.UserUtil;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 新增事件广告计划关联的后置函数
 * @author asq
 * @createTime 2025年3月1日 14:01:20
 */
@Slf4j
public class EventAdPlanAddFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "新增事件广告计划关联后置函数";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		log.info("新增事件广告计划关联后置函数...");
		return createEventPlan(me, param, result);
	}

	/**
	 * 创建旅程相关的营销策略，策略广告，广告计划
	 * @param result
	 */
	private Entity createEventPlan(LoginBean me, JSONObject param, AjaxResult result) {
		// 构造param
		JSONObject paramObj = JSONUtil.createObj();
		String configId = param.getStr("config_id");
		Entity config = Db.createSqlParser("event_ad_config").where("main_id", configId).findOne(me.getDataSource());
		String eventType = param.getStr("event_type");
		String eventTypeName = Db.createSqlParser("sys_event_type").select("name").where("event_type", eventType).val();
		String eventKey = param.getStr("event_key");
		String eventKeyName = Db.createSqlParser("sys_event").select("event_name").where("event_key", eventKey).val();

		paramObj.set("name", "事件：" + config.getStr("config_name") + "-" + eventTypeName + "-" + eventKeyName);
		paramObj.set("source_id", result.get(ICall.MAIN_ID));
		paramObj.set("source_type", "event");
		paramObj.set("user_refresh_type", 1);
		paramObj.set("cycle_type", "PERMANENT");
		paramObj.set("priority", 1);
		paramObj.set("exec_type", 1);
		paramObj.set("audience_rule", config.get("audience_rule"));
		paramObj.set("app_rule", config.getStr("app_rule"));

		// 创建营销策略，策略广告，广告计划
		createPlanByStage(paramObj);

		Entity entity = Entity.create("event_ad_plan_config");
		entity.set("main_id", result.get(ICall.MAIN_ID));
		entity.set("plan_id", paramObj.get("plan_id"));
		entity.set("campaign_id", paramObj.get("campaign_id"));
		entity.set("status", -1);

		Db.insert(me.getDataSource(), entity);
		
		return entity;
	}

	/**
	 * 根据旅程创建营销策略，策略广告，广告计划
	 * @param param 旅程
	 */
	private void createPlanByStage(JSONObject param) {
		long tenantId = UserUtil.getLoginUser().getTenantId();
		StreamLoadConfig config = DbConfig.useTenantSLC(tenantId);

		List<Entity> dataList = new CopyOnWriteArrayList<>();

		// 创建营销策略，策略广告，广告计划
		Entity adCampaign = PlanHelper.generateCampaign(param);
		dataList.add(adCampaign);
		Entity adPlan = PlanHelper.generatePlan(param);

		dataList.add(adPlan);

		// 保存
		Db.insertBatchWithStream(config, dataList);
	}

}
